import { Button, Card, Dropdown, Input, Popconfirm, Space, Spin, Table, Tree, Upload, Descriptions } from 'antd';
import { useState, useEffect, useRef } from 'react'
// import _ from 'lodash';
import FetchHelper from '../../../../../utils/helper/fetch-helper';
import AddModal from './AddModal';

//系统数库未同步，先写功能，2024.3.10
export default function Bu_men(props) {

    //登录用户id
    const [user_id, setUser_id] = useState();
    //登录用户信息
    const [user_xx, setUser_xx] = useState();
    //预设用户信息
    const [preset_user_xx, setPreset_user_xx] = useState();
    //预设部门id
    const [preset_dept_id, setPreset_dept_id] = useState();
    //用户部门信息
    const [preset_dept, setPreset_dept] = useState(
        //此为模拟数据，
        {
            id: "2001",
            createBy: null,
            createTime: "2024-02-29 18:59:40",
            deleted: null,
            updateBy: 1,
            updateTime: "2024-02-29 18:59:40",
            accountLevels: null,
            ancestors: [{
                id: "2003",
                createBy: null,
                createTime: "2024-02-29 18:59:40",
                deleted: null,
                updateBy: 1,
                updateTime: "2024-02-29 18:59:40",
                accountLevels: null,
                ancestors: null,
                parentId: 2002,
                code: "jz",
                deptName: "部门001_01"
            }, {
                id: "2004",
                createBy: null,
                createTime: "2024-02-29 18:59:40",
                deleted: null,
                updateBy: 1,
                updateTime: "2024-02-29 18:59:40",
                accountLevels: null,
                ancestors: null,
                parentId: 2002,
                code: "jz",
                deptName: "部门001_02"
            }, {
                id: "2005",
                createBy: null,
                createTime: "2024-02-29 18:59:40",
                deleted: null,
                updateBy: 1,
                updateTime: "2024-02-29 18:59:40",
                accountLevels: null,
                ancestors: null,
                parentId: 2002,
                code: "jz",
                deptName: "部门001_03"
            }, {
                id: "2006",
                createBy: null,
                createTime: "2024-02-29 18:59:40",
                deleted: null,
                updateBy: 1,
                updateTime: "2024-02-29 18:59:40",
                accountLevels: null,
                ancestors: null,
                parentId: 2002,
                code: "jz",
                deptName: "部门001_04"
            }, {
                id: "2007",
                createBy: null,
                createTime: "2024-02-29 18:59:40",
                deleted: null,
                updateBy: 1,
                updateTime: "2024-02-29 18:59:40",
                accountLevels: null,
                ancestors: null,
                parentId: 2002,
                code: "jz",
                deptName: "部门001_05"
            },
            ],
            parentId: "",
            code: "jz",
            deptName: "部门001"
        }
    );
    //用户部门信息
    const [preset_dept_xx, setPreset_dept_xx] = useState();

    const [addOpen, setAddOpen] = useState();

    const [total, setTotal] = useState();
    const [allColumns, setAllColumns] = useState();
    const [loading, setLoading] = useState();
    const rootRef = useRef();

    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1,

    });

    useEffect(() => {
        FetchHelper.getJson(`/admin-api/getInfo`).then(resp => {
            console.log('1')
            //拿到登录用户的id,userId
            console.log(resp?.data?.user?.userId)
            setUser_id(resp?.data?.user?.userId)
            setUser_xx(resp?.data?.user)


        })
    }, [])

    //用登录用户id找到对应的预设用户
    useEffect(() => {
        if (user_id) {
            console.log('2')
            FetchHelper.getJson(`/admin-api/ybyj/presetUser/list?originalUserId=${user_id}`,).then(resp => {
                console.log('2',resp)
                setPreset_dept_id(resp?.rows?.[0]?.presetDeptId)
                setPreset_user_xx(resp?.rows)
            })
        } else {
            //
        }
    }, [user_id])

    //预设用户找到预设部门的祖籍部门：ancestors。
    useEffect(() => {
        if (preset_dept_id) {
            console.log('3')

            FetchHelper.getJson(`/admin-api/ybyj/presetDept/${preset_dept_id}`).then(resp => {
                setPreset_dept_xx(resp?.data)
                console.log('3',resp?.data)

                //部门名称：deptName，resp.data.deptName

                //权限标识：code

                //祖籍部门：ancestors
                //setPreset_dept(resp?.data)

            })
        } else {
            //
        }
    }, [preset_dept_id])


    /* 
    # 权限模块 api

## 查询出当前用户及下辖所有子部门。用于界面展示部门树。（这里只能查询到自己能够管理的部门

    实现方式为: 查询当前用户的部门获取到ancestors。查询预设部门表条件为：where ancestors like '$1%'。即可将当前用户能够管理的部门列表查出

## 新增部门。前端传递上级部门。校验上级部门是否自己能够管理的部门列表中。校验部门等级是否低于当前用户所在部门等级，如果没有传递，就在当前用户所在部门等级上 + 1。最大为3。

    新增部门的ancestors参考原有部门新增实现

## 删除部门。校验删除的部门id是否在自己能够管理的部门列表中，校验部门是否还有下级部门，如果有下级部门，则不能删除。

## 编辑部门。编辑名称、权限


## 查询部门下的用户。直接查询预设用户表，根据部门id进行关联查询。

## 新增部门用户，校验传递的部门id是否在自己能够管理的部门列表中。

## 编辑部门用户。修改名字。手机号。或者部门。如果传递了部门id就判断部门id是否在自己能够管理的部门列表中

## 删除用户。只能删除自己能够管理的部门列表中的用户。

## 绑定和解绑用户。
 */


    const onSearch = (value) => {

        console.log(value)
        const targetDiv = document.getElementById(value);
        if (targetDiv) {
            targetDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else {
            console.log('1', value)
            alert(`未找到编号为 '${value}' 的部门`);
        }

    }
    // console.log('params',params)
    // const [messageApi,contentHolder]=Message.useMessage();

    const handleJudge = () => {



    }


    const columns = [
        {
            title: '用户账号',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '用户密码',
            key: 'password',
            dataIndex: 'password',
        },
        {
            title: '用户昵称',
            dataIndex: 'nickName',
            key: 'nickName',
        },
        {
            title: '用户类型',
            dataIndex: 'userType',
            key: 'address',
        },
        {
            title: '用户邮箱',
            key: 'email',
            dataIndex: 'email',
        }
        ,
        {
            title: '用户电话',
            key: 'phonenumber',
            dataIndex: 'phonenumber',
        },
        {
            title: '管理',
            // key: 'qxgl',
            // dataIndex: 'qxgl',
            render: (t, record) => {

                return <>
                    <Button type="link" size='small' onClick={e => {

                    }}>信息修改</Button>
                    <Button type="link" size='small' onClick={e => {

                    }} style={{ color: "red" }}>删除用户</Button>
                </>
            }
        }


    ];
    const data = [
        {
            key: '1',
            userName: '蜀安',
            password: 888888254,
            nickName: '蜀安',
            userType: "普通用户",
            email: "234245535@qq.com",
            phonenumber: 13423453452,

        },
        {
            key: '2',
            userName: '蜀安',
            password: 888888254,
            nickName: '蜀安',
            userType: "普通用户",
            email: "234245535@qq.com",
            phonenumber: 13423453452,

        },
        {
            key: '3',
            userName: '蜀安',
            password: 888888254,
            nickName: '蜀安',
            userType: "普通用户",
            email: "234245535@qq.com",
            phonenumber: 13423453452,

        },
    ];


    // //新增部门
    // const addDept = () => {

    //     FetchHelper.postJson(`/admin-api/ybyj/presetDept`, {
    //         code: code_code,
    //         deptName: dept_name,
    //         ancestors: preset_dept.ancestors,
    //         parentId: preset_dept.id
    //     }).then(resp => {

    //         console.log(resp?.data?.user)
    //         setUser_id(resp?.data?.user?.userId)
    //         setUser_xx(resp?.data?.user)


    //     })
    // }



    return <div className='layout-h h100'>

        <Card size="small" className='h100 fill w0' style={{
            position: "relative",
        }} bodyStyle={{

            display: "flex",
            flexDirection: "column",
            height: "100%",

        }}>
            <div style={{
                // marginBottom: 12,
                // display: 'flex',
                // alignItems: "center",
                // justifyContent: "space-between",
                height: 300,
            }}>
                {/* 样式还待设置，数据以模拟展示，具体数据要等系统重新部署后才能处理 */}
                <Descriptions title="基本信息">
                    <Descriptions.Item label="用户昵称" key="1" children={user_xx?.nickName ? user_xx.nickName : "未设置昵称"} />
                    <Descriptions.Item label="用户性别" key="2" children={user_xx?.sex ? (user_xx.sex === '1' ? "女" : user_xx.sex === '0' ? "男" : "未知") : "未设置"} />
                    <Descriptions.Item label="用户电话" key="3" children={user_xx?.phonenumber ? user_xx.phonenumber : "未绑定电话"} />
                    <Descriptions.Item label="用户类型" key="4" children={user_xx?.remark ? user_xx.remark : "未设置"} />
                    <Descriptions.Item label="所属部门" key="5" children={preset_dept_xx?.deptName} />
                    <Descriptions.Item label="上级部门" key="6" children={preset_dept_xx?.parentId==='-1'?'无上级部门':'待完善'} />
                    <Descriptions.Item label="下属部门" key="7" children={preset_dept.ancestors.map((e, index) => {
                        return <span key={index} style={{ marginRight: 30 }}>{e.deptName}（编号：{e.id}）</span>;
                    })} />
                </Descriptions>




                {/* 
                //username，county，accountLevel，job，phonenumber，isBinding，_,_,remark
                <div>用户昵称 ： {user_xx?.nickName ? user_xx.nickName : "未设置昵称"}</div>
                <div>用户区县 ： {user_xx?.remark ? user_xx?.remark : "未设置"}</div>
                <div>账户等级 ： {preset_dept.deptName}</div>
                <div>用户职务 ： {user_xx?.sex ? user_xx.sex === '1' ? "女" : user_xx?.sex === '0' ? "男" : "未知" : "未设置"}</div>
                <div>用户电话 ： {user_xx?.phonenumber ? user_xx?.phonenumber : "未绑定电话"}</div>
                <div>是否绑定 ： {user_xx?.remark ? user_xx?.remark : "未设置"}</div>
                <div>所属部门 ： {preset_dept.deptName}</div>
                <div>上级部门 ： {preset_dept.parentId}</div>
                <div>下属部门 ： {preset_dept.ancestors.map(e => {
                    return <span style={{ marginRight: 10 }}>{e.deptName}</span>
                })}</div>
                <div>备注 ： {preset_dept.deptName}</div>
                 */}

            </div>
            <hr style={{
                width: "100%"
            }} />
            <div style={{
                marginBottom: 12,
                display: 'flex',
                alignItems: "center",
                justifyContent: "space-between"
            }}>

                <Space>
                    <>
                        <Button onClick={e => { setAddOpen(true) }}>新增部门</Button>
                    </>
                </Space>

                <div>
                    <Input.Search placeholder='输入部门名称查找'
                        allowClear
                        enterButton={true}
                        onSearch={onSearch}
                    />
                </div>
            </div>
            <Card style={{ overflow: "auto" }}>

                {preset_dept.ancestors.map(e => {
                    return (
                        <Card id={e.id} title={e.deptName} style={{ marginBottom: "30px" }} headStyle={{ background: "#001529", color: "#fff" }}>
                            <div style={{
                                marginBottom: 12,
                                display: 'flex',
                                alignItems: "center",
                                justifyContent: "space-between"
                            }}>

                                <Space>
                                    <>
                                        <Button type="primary" onClick={() => handleJudge}>新增部门用户</Button>
                                        <Input.Search placeholder='输入名称查找'
                                            allowClear
                                            enterButton={true}
                                            onSearch={onSearch}
                                        />
                                        <Button style={{ backgroundColor: '#8B0000', color: 'white' }} onClick={() => handleJudge}>删除部门</Button>
                                    </>
                                </Space>

                                <div>


                                </div>

                            </div>
                            <Table columns={columns} dataSource={data}>

                            </Table>
                        </Card>
                    )
                })}
            </Card>

        </Card>
        <AddModal open={addOpen} onCancel={e => {
            setAddOpen(false);
        }}
            preset_dept={preset_dept} setPreset_dept={setPreset_dept} />
        {/* <EditModal jzzyxlDefs={jzzyxlDefs} record={currentRecord} open={editOpen} onCancel={e => {
            setEditOpen(false);
        }} node={node} onOk={e => {
            setEditOpen(false);
            setCurrentRecord(null);
            setParams(p => {
                return {
                    ...p,
                    pageNum: 1
                }
            })
        }} /> */}
    </div>;
}